package 链表.双链表crud;


/**
 * 注意避免curr.next==null curr.next.pre×
 */
public class DoubleLinkedListDemo {
    public static void main(String[] args) {
        DoubleLinkedList sll = new DoubleLinkedList();
        HeroNode2 heroNode1 = new HeroNode2(1, "虚空掠夺者");
        HeroNode2 heroNode2 = new HeroNode2(2, "风暴之怒");
        HeroNode2 heroNode3 = new HeroNode2(3, "盖伦");
        HeroNode2 heroNode4 = new HeroNode2(4, "寒冰");

        sll.add(heroNode1);
        sll.add(heroNode2);
        sll.add(heroNode3);
        sll.add(heroNode4);

        HeroNode2 heroNode = new HeroNode2(4, "寒冰射手");
        sll.update(heroNode);

        sll.del(4);
        sll.list();


    }
}

class DoubleLinkedList {
    public HeroNode2 head = new HeroNode2(0, "");

    public void getHead(HeroNode2 head) {
        this.head = head;
    }

    public void list(){
        HeroNode2 curr = head;
        while (true) {
            if (curr.next == null) {
                break;
            }
            curr = curr.next;
            System.out.println(curr);
        }
    }

    public void add(HeroNode2 heroNode2) {
        HeroNode2 curr = head;

        while (true) {
            if (curr.next == null) {
                break;
            }
            curr = curr.next;
        }
        curr.next = heroNode2;
        heroNode2.prev = curr;
    }

    public void update(HeroNode2 heroNode2){
        HeroNode2 curr = head;
        while (true) {
            if (curr.id == heroNode2.id) {
                curr.name = heroNode2.name;
                break;
            }
            if (curr.next == null) { // 这里的判断必须放在下面
                System.out.println("要修改的英雄编号不存在");
                break;
            }
            curr = curr.next;
        }
    }

    public void del(Integer id){
        HeroNode2 curr = head;
        while (true) {
            if (curr.id == id && curr.next == null) { // 法一：针对删最后一个节点的情况特别判断下
                curr.prev.next = null;
                break;
            }
            if (curr.id == id) {
                curr.prev.next = curr.next;
//                if (curr.next != null) { // 法二：if中继续if判断
//                    curr.next.prev = curr.prev;
//                }
                break;
            }
            if (curr.next == null) {
//                System.out.println("您所删除的英雄编号不存在");
                break;
            }
            curr = curr.next;
        }
    }
}

class HeroNode2 {
    public int id;
    public String name;
    public HeroNode2 next;
    public HeroNode2 prev;

    public HeroNode2(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "HeroNode{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}